package com.bitspilani.infonet;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;

public class AccelerometerHandler implements SensorEventListener {
	private boolean firstSensorValue = true;
	private float lastValueX, lastValueY, lastValueZ;
	private float gravityX = 0, gravityY = 0, gravityZ = 0;
	
	private MainActivity mainActivity = new MainActivity();
	
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER){

			float mSensorX = event.values[0] - gravityX;
			float mSensorY = event.values[1] - gravityY;
			float mSensorZ = event.values[2] - gravityZ;//removing the effect of gravity from the sensor

			MainActivity.setAccTextView("mSensorX: "+mSensorX+", mSensorY: "+mSensorY+", mSensorZ: "+mSensorZ);


			if(firstSensorValue){
				lastValueX = mSensorX;
				lastValueY = mSensorY;
				lastValueZ = mSensorZ;
				firstSensorValue = false;
			}else{
				if((lastValueX - mSensorX > Constants.DECELERATION_THRESHOLD) ||
						(lastValueY - mSensorY > Constants.DECELERATION_THRESHOLD) ||
						(lastValueZ - mSensorZ > Constants.DECELERATION_THRESHOLD) ){
					
					mainActivity.relaxListning();
					mainActivity.playNotificationSound();
					restVariables();
					
					System.out.println(">>>>>> Panic Braked");
					MainActivity.setAccTextView("PANIC BRAKED");

				}else{
					System.out.println("<NORMAL>"+(lastValueX - mSensorX) +" "+(lastValueY - mSensorY)+" "+(lastValueZ - mSensorZ));
				}

				lastValueX = mSensorX;
				lastValueY = mSensorY;
				lastValueZ = mSensorZ;
				


			}

		}else if(event.sensor.getType() != Sensor.TYPE_GRAVITY)	{
			System.out.println("GRAVITY>: "+gravityX+" "+gravityY+" "+gravityZ);
			gravityX= event.values[0];
			gravityY = event.values[1];
			gravityZ = event.values[2] ;
		}
	}
private void restVariables(){
	lastValueX = 0;
	lastValueY = 0;
	lastValueZ= 0;
	gravityX=  0;
	gravityY  = 0;
	gravityZ  = 0;
}


}
